/**
 * @author yxw
 * date : 2013年9月30日 下午3:47:12 
 */
package com.tzinfo.tzt.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.activity.view.ImageAdapter;
import com.tzinfo.tzt.activity.view.XListView;
import com.tzinfo.tzt.activity.view.XListView.IXListViewListener;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.domain.FjhMovList;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.NewhouseList;
import com.tzinfo.tzt.domain.NewhouseNewsDetail;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;
import com.tzinfo.tzt.R;

public class FjhInterviewTabActivity extends BaseActivity implements IXListViewListener {

	// UI组件
	private XListView videoListView;
	private List<Map<String, Object>> videoData;
	private ImageAdapter videoSimpleAdapter;
	private Handler mHandler;

	private MyResultList movListResult;

	private int pageNum = 1;
	private static final int pageSize = 10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fjh_interview_tab);
		init();
	}

	private void init() {
		mHandler = new Handler();
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar_loding);
		// 加载进度条
		showProgressBar();
		videoListView = (XListView) this.findViewById(R.id.listview_fjh_video);
		videoListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				//尚未开通
				TextView idText = (TextView) view
						.findViewById(R.id.un_video_id);
				TextView urlText = (TextView) view
						.findViewById(R.id.un_video_url);
				
				Intent intent = new Intent(FjhInterviewTabActivity.this,
						VideoPlayActivity.class);
				intent.putExtra("videoId", idText.getText() + "");
				intent.putExtra("videoUrl", urlText.getText() + "");
				startActivity(intent);
				
//				Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(urlText.getText() + ""));
//		        startActivity(intent);
				
//				Toast.makeText(FjhInterviewTabActivity.this, "视频播放功能尚未开通，敬请期待~！", 5000).show();

			}
		});
		videoListView.setXListViewListener(this);
		videoListView.setPullLoadEnable(true);
		initData();
	}
	private void initData() {
		pageNum = 1;
		// 通过线程访问网络得到数据
		new Thread(getNewHouseNewsListRun).start();
	}
	
	
	private void updateUI() {
		videoSimpleAdapter = new ImageAdapter(this, videoData,
				R.layout.item_fjh_mov_list, new String[] { "ID", "Title",
						"Logo", "Movies" }, new int[] { R.id.un_video_id,
						R.id.list_fjh_video_title, R.id.list_item_image,
						R.id.un_video_url });
		videoListView.setAdapter(videoSimpleAdapter);
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				getDataError((String) msg.obj);
				break;
			case 1:
				updateUI();
				if (videoListView.getFooterViewsCount() == 0) {
					videoListView.addFooterView(videoListView.getmFooterView());
				}
				removeProgressBar();
				onLoad();
				break;
			case 2:
				if (videoListView.getFooterViewsCount() == 0) {
					videoListView.addFooterView(videoListView.getmFooterView());
				}
				videoSimpleAdapter.notifyDataSetChanged();
				onLoad();
				break;
			case 3:
				showLastRow();
				if (videoListView.getFooterViewsCount() > 0) {
					videoListView.removeFooterView(videoListView.getmFooterView());
				}
				onLoad();
				break;
			case 4:
				// 没有数据
				updateUI();
				videoData.clear();
				if (videoListView.getFooterViewsCount() > 0) {
					videoListView.removeFooterView(videoListView.getmFooterView());
				}
				videoSimpleAdapter.notifyDataSetChanged();
				// xListView.setVisibility(View.GONE);
				removeProgressBar();
				onLoad();
				break;
			case 5:
				updateUI();
				onLoad();
				// 只有一页
				if (videoListView.getFooterViewsCount() > 0) {
					videoListView.removeFooterView(videoListView.getmFooterView());
				}
				removeProgressBar();
				break;
			case 0:
				break;
			}
		}
	};
	
	protected void showLastRow() {
		Toast.makeText(this, "已经是最后一页！", 5000).show();
	}
	/**
	 * 线程 得到新房列表
	 */
	Runnable getNewHouseNewsListRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();

			String jsonString;
			String url = AppDataConfig.fjhUrl + AppDataConfig.FjhMovList
					+ "?pagenumber=" + pageNum + "&pagesize=" + pageSize;
			Log.e("url", url);
			jsonString = HttpTools.getJsonContent(url, "gb2312");
			Log.e("JsonString2", jsonString);
			movListResult = JsonTools.getFjhMovList(jsonString);
			getData();
			if (movListResult.getSuccess()) {
				if (movListResult.getData().size() == 0) {
					msg.arg1 = 4;
				} else if (movListResult.getData().size() < pageSize) {
					msg.arg1 = 5;
				} else {
					msg.arg1 = 1;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = movListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};
	
	/**
	 * 线程 得到新房列表
	 */
	Runnable getMoreNewHouseNewsListRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();

			String jsonString;
			String url = AppDataConfig.fjhUrl + AppDataConfig.FjhMovList
					+ "?pagenumber=" + pageNum + "&pagesize=" + pageSize;
			Log.e("url", url);
			jsonString = HttpTools.getJsonContent(url, "gb2312");
			Log.e("JsonString2", jsonString);
			movListResult = JsonTools.getFjhMovList(jsonString);
			getMoreData();
			if (movListResult.getSuccess()) {
				if (movListResult.getData().size() == 0) {
					msg.arg1 = 3;
				} else {
					msg.arg1 = 2;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = movListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	// 得到data数据
	private void getData() {
		videoData = new ArrayList<Map<String, Object>>();
		List<Object> movList;
		Map<String, Object> movMap;
		if (movListResult.getSuccess()) {
			Log.e("size", movListResult.getData().size() + "");
			movList = movListResult.getData();
			for (int i = 0; i < movList.size(); i++) {
				movMap = new HashMap<String, Object>();
				FjhMovList fjhMovList = (FjhMovList) movList.get(i);
				movMap.put("ID", fjhMovList.getID());
				movMap.put("Title", fjhMovList.getTitle());
				movMap.put("Logo", fjhMovList.getLogo());
				movMap.put("Movies", fjhMovList.getMovies());
				videoData.add(movMap);
			}
		}
	}
	private void getMoreData(){
		List<Object> movList;
		Map<String, Object> movMap;
		if (movListResult.getSuccess()) {
			Log.e("size", movListResult.getData().size() + "");
			movList = movListResult.getData();
			for (int i = 0; i < movList.size(); i++) {
				movMap = new HashMap<String, Object>();
				FjhMovList fjhMovList = (FjhMovList) movList.get(i);
				movMap.put("ID", fjhMovList.getID());
				movMap.put("Title", fjhMovList.getTitle());
				movMap.put("Logo", fjhMovList.getLogo());
				movMap.put("Movies", fjhMovList.getMovies());
				videoData.add(movMap);
			}
		}
	}
	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						showProgressBar();
						new Thread(getNewHouseNewsListRun).start();
					}
				}).show();
	}


	private void onLoad() {
		videoListView.stopRefresh();
		videoListView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		videoListView.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				// getData();
				// 如果刷新后数据不变，会出错
				// simpleAdapter.notifyDataSetChanged();
				// newAdapter();
				// xListView.setAdapter(simpleAdapter);
				pageNum = 1;
				initData();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				pageNum++;
				new Thread(getMoreNewHouseNewsListRun).start();

			}
		}, 2000);
	}

}
